<template>
    <div v-show="visible" class="w-[440px] min-w-[440px] max-w-[440px] flex flex-col h-full px-0 pt-4 pb-0 bg-[#232428] relative select-none z-10">
        <!-- 顶部标题栏 -->
        <div class="mx-6 mb-6">
            <div class="text-xl font-bold text-white leading-none">Image Generation</div>
        </div>
        <!-- 上传区 -->
        <div class="w-full text-[#bfc0c2] text-sm mx-6 mb-2">Upload Reference Image</div>
        <div class="rounded-md flex flex-col items-center mx-6 bg-[#232428]">
            <div class="w-full relative">
                <div class="relative flex flex-col items-center justify-center h-36 rounded-lg bg-[#18191c] border border-[#232428] shadow">
                    <template v-if="image.url">
                        <img :src="image.url" class="w-full h-full object-cover rounded-lg" />
                        <div class="absolute top-1 right-1 bg-[#232428] rounded-full p-1 cursor-pointer" @click="removeImage">
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#bfc0c2" stroke-width="2">
                                <path d="M18 6L6 18M6 6l12 12" stroke-linecap="round" stroke-linejoin="round"/>
                            </svg>
                        </div>
                    </template>
                    <template v-else>
                        <div class="flex flex-col items-center justify-center w-full h-full">
                            <input
                                type="file"
                                accept="image/jpeg,image/png"
                                class="hidden"
                                ref="fileInputRef"
                                @change="handleFileUpload"
                            />
                            <div class="flex flex-col items-center justify-center w-full h-full cursor-pointer" @click="() => fileInputRef?.click()">
                                <svg class="mb-2" width="28" height="28" fill="none" stroke="#bfc0c2" stroke-width="2" viewBox="0 0 48 48">
                                    <rect x="8" y="8" width="32" height="32" rx="6" fill="#232428"/>
                                    <path d="M16 32l8-8 8 8" stroke="#bfc0c2" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                                    <path d="M24 24V16" stroke="#bfc0c2" stroke-width="2" stroke-linecap="round"/>
                                </svg>
                                <div class="text-[#bfc0c2] text-sm font-bold mb-1">Upload Image</div>
                                <div class="text-[#bfc0c2] text-xs">
                                    <span class="text-[#bfc0c2]">(Required)</span>
                                </div>
                            </div>
                        </div>
                    </template>
                </div>
            </div>
        </div>
        <!-- 创意描述输入区 -->
        <div class="mx-6 mt-4 mb-4">
            <div class="flex items-center gap-2 mb-2">
                <span class="text-[#bfc0c2] text-sm font-bold">Creative Description (Required)</span>
            </div>
            <textarea
                v-model="prompt"
                class="w-full h-28 rounded-md bg-[#232428] border border-neutral-700 text-[#bfc0c2] text-sm p-3 resize-none focus:outline-none focus:ring-1"
                style="line-height: 20px;"
                placeholder="Please describe the video content you want to generate, or use DeepSeek to describe the image, you can also check the User Guide to improve generation results"></textarea>
        </div>
        <!-- 不希望呈现的内容输入区 -->
        <div class="mx-6 mt-4 mb-2">
            <div class="flex items-center gap-2 mb-2">
                <span class="text-[#bfc0c2] text-sm font-bold">Content Not to Show (Optional)</span>
            </div>
            <textarea
                v-model="negativePrompt"
                class="w-full h-28 rounded-md bg-[#232428] border border-neutral-700 text-[#bfc0c2] text-sm p-3 resize-none focus:outline-none focus:ring-1"
                style="line-height: 20px;"
                placeholder="Write down what you don't want to show in the video. For example: animation, blur, distortion, disfigurement, low quality, collage, grainy, logo, abstract, illustration, computer-generated, distortion..."></textarea>
        </div>
        <!-- 下拉和按钮吸底区域 -->
        <div class="absolute left-0 bottom-0 w-full px-6 pb-6 bg-[#232428] z-20">
            <div class="flex flex-col gap-4">
                <!-- 下拉菜单区 -->
                <div class="flex items-center gap-2">
                    <div class="relative flex-1">
                        <div @click="showModeDropdown = !showModeDropdown"
                            class="flex items-center justify-between w-full h-10 px-4 rounded-md border border-[#bfc0c2]/40 bg-[#232428] cursor-pointer text-sm text-[#bfc0c2] focus:ring-0 focus:outline-none transition-all">
                            <span class="text-[#7fff00] leading-none">{{ modeOptions.find(opt => opt.value === selectedMode)?.label }}</span>
                            <svg :class="['w-4 h-4 ml-2 text-[#bfc0c2] transition-transform duration-200', showModeDropdown ? 'rotate-180' : '']"
                                fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" d="M19 9l-7 7-7-7" />
                            </svg>
                        </div>
                        <transition enter-active-class="transition-all duration-200 ease-in-out"
                            leave-active-class="transition-all duration-200 ease-in-out"
                            enter-from-class="translate-y-4 opacity-0"
                            enter-to-class="translate-y-0 opacity-100"
                            leave-from-class="translate-y-0 opacity-100"
                            leave-to-class="translate-y-4 opacity-0">
                            <div v-if="showModeDropdown"
                                class="absolute left-0 bottom-full mb-2 w-full rounded-md bg-[#18191c] border border-[#18191c] z-30 overflow-hidden">
                                <div v-for="opt in modeOptions" :key="opt.value"
                                    @click="selectMode(opt.value)"
                                    class="px-6 py-4 cursor-pointer text-sm font-bold transition-all duration-200"
                                    :class="[
                                        selectedMode === opt.value
                                            ? 'bg-[#18191c] text-[#7fff00]'
                                            : 'bg-[#18191c] text-white hover:bg-[#232428] hover:text-[#7fff00]',
                                        opt.value === 1 ? 'rounded-t-md' : 'rounded-b-md',
                                        'flex items-center gap-2'
                                    ]">
                                    {{ opt.label }}
                                    <span v-if="opt.value === 2"
                                        class="ml-2 text-xs bg-[#1e2d1b] text-[#7fff00] px-2 py-0.5 rounded-md font-bold">VIP</span>
                                </div>
                            </div>
                        </transition>
                    </div>
                    <div class="relative flex-1">
                        <div @click="showDurationDropdown = !showDurationDropdown"
                            class="flex items-center justify-between w-full h-10 px-4 rounded-md border border-[#bfc0c2]/40 bg-[#232428] cursor-pointer text-sm text-[#bfc0c2] focus:ring-0 focus:outline-none transition-all">
                            <span class="text-[#7fff00] leading-none">{{ durationOptions.find(opt => opt.value === selectedDuration)?.label }}</span>
                            <svg :class="['w-4 h-4 ml-2 text-[#bfc0c2] transition-transform duration-200', showDurationDropdown ? 'rotate-180' : '']"
                                fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" d="M19 9l-7 7-7-7" />
                            </svg>
                        </div>
                        <transition enter-active-class="transition-all duration-200 ease-in-out"
                            leave-active-class="transition-all duration-200 ease-in-out"
                            enter-from-class="translate-y-4 opacity-0"
                            enter-to-class="translate-y-0 opacity-100"
                            leave-from-class="translate-y-0 opacity-100"
                            leave-to-class="translate-y-4 opacity-0">
                            <div v-if="showDurationDropdown"
                                class="absolute left-0 bottom-full mb-2 w-full rounded-md bg-[#18191c] border border-[#18191c] z-30 overflow-hidden">
                                <div v-for="opt in durationOptions" :key="opt.value"
                                    @click="selectDuration(opt.value)"
                                    class="px-6 py-4 cursor-pointer text-sm font-bold transition-all duration-200"
                                    :class="[
                                        selectedDuration === opt.value
                                            ? 'bg-[#18191c] text-[#7fff00]'
                                            : 'bg-[#18191c] text-white hover:bg-[#232428] hover:text-[#7fff00]',
                                        opt.value === 1 ? 'rounded-t-md' : 'rounded-b-md',
                                        'flex items-center gap-2'
                                    ]">
                                    {{ opt.label }}
                                </div>
                            </div>
                        </transition>
                    </div>
                    <div class="relative flex-1">
                        <div @click="showRatioDropdown = !showRatioDropdown"
                            class="flex items-center justify-between w-full h-10 px-4 rounded-md border border-[#bfc0c2]/40 bg-[#232428] cursor-pointer text-sm text-[#bfc0c2] focus:ring-0 focus:outline-none transition-all">
                            <span class="text-[#7fff00] leading-none">{{ ratioOptions.find(opt => opt.value === selectedRatio)?.label }}</span>
                            <svg :class="['w-4 h-4 ml-2 text-[#bfc0c2] transition-transform duration-200', showRatioDropdown ? 'rotate-180' : '']"
                                fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" d="M19 9l-7 7-7-7" />
                            </svg>
                        </div>
                        <transition enter-active-class="transition-all duration-200 ease-in-out"
                            leave-active-class="transition-all duration-200 ease-in-out"
                            enter-from-class="translate-y-4 opacity-0"
                            enter-to-class="translate-y-0 opacity-100"
                            leave-from-class="translate-y-0 opacity-100"
                            leave-to-class="translate-y-4 opacity-0">
                            <div v-if="showRatioDropdown"
                                class="absolute left-0 bottom-full mb-2 w-full rounded-md bg-[#18191c] border border-[#18191c] z-30 overflow-hidden">
                                <div v-for="opt in ratioOptions" :key="opt.value"
                                    @click="selectRatio(opt.value)"
                                    class="px-6 py-4 cursor-pointer text-sm font-bold transition-all duration-200"
                                    :class="[
                                        selectedRatio === opt.value
                                            ? 'bg-[#18191c] text-[#7fff00]'
                                            : 'bg-[#18191c] text-white hover:bg-[#232428] hover:text-[#7fff00]',
                                        opt.value === 1 ? 'rounded-t-md' : 'rounded-b-md',
                                        'flex items-center gap-2'
                                    ]">
                                    {{ opt.label }}
                                </div>
                            </div>
                        </transition>
                    </div>
                </div>
                <!-- 生成按钮 -->
                <button
                    @click="handleGenerate"
                    :disabled="!canGenerate"
                    class="w-full bg-[#7fff00] hover:bg-[#5fd700] text-[#232428] font-bold h-12 rounded-md text-lg mt-2 transition-all disabled:opacity-50 disabled:cursor-not-allowed">
                    Generate Now
                </button>
            </div>
        </div>
    </div>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue';
import { getImage2Image, getPicResult } from '@/api';
import { Message } from '@arco-design/web-vue';
import Upload from '@/utils/Upload';

// 图片类型
export interface ImageType {
    url: string;
    file?: File;
}

// 图片生成状态
interface PicTaskResult {
    task_status: number;
    task_result: string;
    task_msg: string;
}

export default defineComponent({
    name: 'ImageAgent',
    components: {
    },
    props: {
        visible: {
            type: Boolean,
            default: false
        }
    },
    emits: ['image-generated'],
    setup() {
        const fileInputRef = ref<HTMLInputElement | null>(null);
        return {
            fileInputRef
        };
    },
    data() {
        return {
            image: { url: '' } as ImageType,
            prompt: '',
            negativePrompt: '',
            showModeDropdown: false,
            modeOptions: [
                { label: 'Standard Mode', value: 1 }
            ],
            selectedMode: 1,
            showDurationDropdown: false,
            durationOptions: [
                { label: '1 Image', value: 1 },
            ],
            selectedDuration: 1,
            showRatioDropdown: false,
            ratioOptions: [
                { label: '9:16', value: 1 }
            ],
            selectedRatio: 1,
            isGenerating: false,
            pollingTimer: null as number | null,
            taskId: ''
        }
    },
    computed: {
        canGenerate(): boolean {
            return this.image.url !== '' && 
                   this.prompt.trim() !== '' && 
                   !this.isGenerating;
        }
    },
    methods: {
        async handleFileUpload(event: Event) {
            const input = event.target as HTMLInputElement;
            if (!input.files?.length) return;

            const file = input.files[0];
            
            // 验证文件类型
            if (!['image/jpeg', 'image/png'].includes(file.type)) {
                Message.error('Only JPG/PNG format images are supported');
                return;
            }

            // 验证文件大小
            if (file.size > 10 * 1024 * 1024) {
                Message.error('Image size cannot exceed 10MB');
                return;
            }

            try {
                const url = await Upload(file, 'image');
                this.image = { url, file };
            } catch (error) {
                Message.error('Upload failed, please try again');
                console.error('Upload error:', error);
            }

            // 清空input，允许重复上传同一文件
            input.value = '';
        },

        removeImage() {
            this.image = { url: '' };
        },

        async handleGenerate() {
            if (!this.canGenerate) return;

            try {
                this.isGenerating = true;
                Message.loading({
                    content: 'Image generation in progress...',
                    duration: 0,
                    closable: true
                });

                const params = {
                    img: this.image.url,
                    prompt: this.prompt.trim(),
                    negative_prompt: this.negativePrompt.trim()
                };

                const response = await getImage2Image(params);
                this.taskId = response.data;
                
                // 立即执行一次状态查询，然后开始轮询
                await this.checkTaskStatus();
                this.startPolling();
            } catch (error) {
                console.error('Generate error:', error);
                Message.error('Generation failed, please try again');
                this.isGenerating = false;
            }
        },

        async checkTaskStatus() {
            try {
                const response = await getPicResult({ task_id: this.taskId });
                const result = response.data as PicTaskResult;

                if (result.task_status === 2) { // 成功
                    this.stopPolling();
                    Message.clear();
                    Message.success('Image generation successful');
                    this.$emit('image-generated', result.task_result);
                    this.isGenerating = false;
                    return true;
                } else if (result.task_status === 3) { // 失败
                    this.stopPolling();
                    Message.clear();
                    Message.error(result.task_msg || 'Image generation failed');
                    this.isGenerating = false;
                    return true;
                }
                return false; // 继续轮询
            } catch (error) {
                console.error('Check status error:', error);
                this.stopPolling();
                Message.clear();
                Message.error('Check task status failed');
                this.isGenerating = false;
                return true; // 发生错误，停止轮询
            }
        },

        async startPolling() {
            if (this.pollingTimer) {
                clearInterval(this.pollingTimer);
            }

            this.pollingTimer = window.setInterval(async () => {
                const shouldStop = await this.checkTaskStatus();
                if (shouldStop) {
                    this.stopPolling();
                }
            }, 5000); // 每5秒轮询一次
        },

        stopPolling() {
            if (this.pollingTimer) {
                clearInterval(this.pollingTimer);
                this.pollingTimer = null;
            }
        },

        selectMode(val: number) {
            this.selectedMode = val;
            this.showModeDropdown = false;
        },
        selectDuration(val: number) {
            this.selectedDuration = val;
            this.showDurationDropdown = false;
        },
        selectRatio(val: number) {
            this.selectedRatio = val;
            this.showRatioDropdown = false;
        }
    },
    mounted() {
        document.body.setAttribute('arco-theme', 'dark');
    },
    beforeUnmount() {
        this.stopPolling();
    }
});
</script>